package com.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: 一个小菜逼
 * @Date: 2020/4/21
 */
public class MySynchronized {


    public static void main(String[] args) {
        CommenData commenData = new CommenData();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    commenData.increase();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();

        new Thread(() -> {
            try {
                for (int i1 = 0; i1 < 10; i1++) {
                    commenData.decrease();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }


}

class CommenData {
    int target;

    public synchronized void increase() throws InterruptedException {
        while (target == 1) {
            //if (target==1){//使用if可能会出现虚假唤醒的情况
            this.wait();
        }
        target++;
        System.out.println(Thread.currentThread().getName() + "tartget:" + target);
        this.notify();
    }

    public synchronized void decrease() throws InterruptedException {
        while (target == 0) {
            //if (target==0){//使用if可能会出现虚假唤醒的情况
            this.wait();
        }
        target--;
        System.out.println(Thread.currentThread().getName() + "tartget:" + target);
        this.notify();
    }
}